package experiment3.task2;

import java.util.*;

/**
 * 仿照hashMap写了一个简易的simpleMap用数组+链表的形式实现
 * 主要功能有：添加、删除、根据key值获取数据、判断key、value是否存在simpleMap中
 *
 * @author 冯永龙
 * @date 2021/4/4 16:03
 */
public class SimpleMap<K, V> implements Map<K, V> {
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //默认容量16
    static final float DEFAULT_LOAD_FACTOR = 0.75f;  //默认负载因子
    static final int MAXIMUM_CAPACITY = 1 << 30;  //最大容量

    static class Node<K, V> implements Map.Entry<K, V> {
        final int hash;
        final K key;
        V value;
        Node<K, V> next;

        public Node(int hash, K key, V value, Node<K, V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        //通过哈希函数获取哈希值
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }


        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?, ?> e = (Map.Entry<?, ?>) o;
                if (Objects.equals(key, e.getKey()) &&
                        Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }

        @Override
        public K getKey() {
            return key;
        }

        @Override
        public V getValue() {
            return value;
        }

        @Override
        public V setValue(V newValue) {
            V oldValue = this.value;
            value = newValue;
            return oldValue;
        }

        @Override
        public String toString() {
            return key + "=" + value;
        }
    }

    //引用HashMap的哈希函数
    static int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    transient Node<K, V>[] table;

    private Integer size = 0; //当前map的大小

    //扩容的零界点 =（capacity*loadFactor)
    int threshold;

    final float loadFactor;

    public SimpleMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }

    public SimpleMap(int initialCapacity, float loadFactor) {
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

    /**
     * hashMap源码，计算最大size
     *
     * @param cap 初始数组长度
     * @return 根据给出的初始数组长度返回容器的最大容量
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

    //获取节点
    final Node<K, V> getNode(int hash, Object key) {
        Node<K, V>[] tab;
        Node<K, V> first, e;
        int n;
        K k;

        if ((tab = table) != null && (n = tab.length) > 0 &&
                (first = tab[(n - 1) & hash]) != null) {

            if (first.hash == hash &&    //如果是第一个节点就返回
                    ((k = first.key) == key || (key != null && key.equals(k))))
                return first;

            if ((e = first.next) != null) {  //如果第一个节点找不到，遍历接下来的节点直到找到为止
                do {
                    if (e.hash == hash &&
                            (((k = e.key) == key) || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

    @Override
    public boolean containsValue(Object value) {
        Node<K, V>[] tab;
        Node<K, V> e;
        V v;
        if ((tab = table) != null && size > 0) {
            //遍历整个table数组，挨个寻找value
            for (int i = 0; i < tab.length; i++) {
                for (e = tab[i]; e != null; e = e.next) {
                    if ((v = e.value) == value ||
                            (value != null && value.equals(v)))
                        return true;
                }
            }
        }
        return false;
    }

    @Override
    public V get(Object key) {
        Node<K, V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    //创建节点
    Node<K, V> newNode(int hash, K key, V value, Node<K, V> next) {
        return new Node<>(hash, key, value, next);
    }

    @Override
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K, V>[] tab;
        Node<K, V> p;
        int n, i;
        //如果table为空或者长度为零就进行扩容
        if ((tab = table) == null || (n = tab.length) == 0) ;
        n = (tab = resize()).length;
        //根据key获取的hash值为数组下标，如果为空就创建新节点
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K, V> e;
            K k;
            //数组该下标处的首位置的key等于插入元素的key，value值覆盖（222行处）
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else { //到该数组下标中的链表中添加元素
                do {
                    //到链表最后一个位置插入新元素
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        break;
                    }

                    //遇到key值相同的元素直接结束循环
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                } while ((e = p.next) != null);
            }
            //表示原Map中存在相同的key,用新value覆盖原来的value
            if (e != null) {
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                return oldValue;
            }
        }

        if (++size > threshold)
            resize();
        return null;
    }

    //hashMap源码的resize()方法
    final Node<K, V>[] resize() {
        Node<K, V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                    oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        } else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int) (DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float) newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float) MAXIMUM_CAPACITY ?
                    (int) ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes", "unchecked"})
        Node<K, V>[] newTab = (Node<K, V>[]) new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K, V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
//                    else if (e instanceof TreeNode) 没有涉及到树所以将这一部分删掉
//                        ((HashMap.TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node<K, V> loHead = null, loTail = null;
                        Node<K, V> hiHead = null, hiTail = null;
                        Node<K, V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            } else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

    @Override
    public V remove(Object key) {
        Node<K, V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
                null : e.value;
    }

    final Node<K, V> removeNode(int hash, Object key, Object value,
                                boolean matchValue, boolean movable) {
        Node<K, V>[] tab;
        Node<K, V> p;
        int n, index;
        Node<K, V> node = null, e;  //node 将要删除的节点
        K k;
        V v;
        //tab[index = (n - 1) & hash]为要删除节点的链表首位置
        if ((tab = table) != null && (n = tab.length) > 0 &&
                ((p = tab[index = (n - 1) & hash]) != null)) {
            if (p.hash == hash &&  //如果p的hash值和key都等于目标值
                    ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;   //将p赋给node
            else if ((e = p.next) != null) {  //遍历table第一个位置的剩下节点
                do {
                    if (e.hash == hash &&  //如果剩下节点的hash值和key值都等于e，就将e赋给node
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        node = e;
                    break;
                } while ((e = e.next) != null);
            }

            if (node != null && (!matchValue || (v = node.value) == value ||
                    (value != null && value.equals(v)))) {
                if (node == p)
                    tab[index] = node.next;
                else
                    p.next = node.next;
                --size;
                return node;
            }
        }
        return null;
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {

    }

    @Override
    public void clear() {
        Node<K, V>[] tab;
        if ((tab = table) != null && size > 0) {
            size = 0;
            for (Node<K, V> node : tab) {
                node = null;
            }
        }
    }

    @Override
    public Set<K> keySet() {
        return null;
    }

    @Override
    public Collection<V> values() {
        return null;
    }

    @Override
    public Set<Entry<K, V>> entrySet() {
        return null;
    }

    @Override
    public String toString() {
        String str = "";
        for (Node<K, V> node : table) {
            if (node != null)
                str += node.toString() + " ";
        }
        return str;
    }

    public static void main(String[] args) {
        SimpleMap simpleMap = new SimpleMap();
        simpleMap.put("1", "张三");
        simpleMap.put("2", "王五");
        System.out.println(simpleMap.toString());
        simpleMap.remove("1");
        boolean containsValue = simpleMap.containsValue("张三");
        boolean containsKey = simpleMap.containsKey("2");
        System.out.println("key：2 是否存在：" + containsKey);
        System.out.println("value:张三 是否存在：" + containsValue);
        System.out.println(simpleMap);
    }
}
